//
//  RJOutModel.m
//  AirQuality
//
//  Created by Po on 15/4/3.
//  Copyright (c) 2015年 Po. All rights reserved.
//

#import "RJOutModel.h"
#import "RJNetWork.h"
#import <MapKit/MKMapView.h>
#import <sqlite3.h>

#define OnedayMS 3670016.000000
@interface RJOutModel () <CLLocationManagerDelegate>

@property (retain, nonatomic) CLLocationManager * currentLocation;
@property (retain, nonatomic) CLLocation *checkinLocation;
@property (strong, nonatomic) NSArray * allAQIArray;
@property (strong, nonatomic) NSArray * oneYear;   //一年数据
@property (strong, nonatomic) NSString * locCityName;

@end

static sqlite3 *_db;
@implementation RJOutModel

- (BOOL)exeSql:(NSString *)sql
{
    char *error;
    sqlite3_exec(_db, sql.UTF8String, NULL, NULL, &error);
    if (error) {
        NSLog(@"%s",error);
        return NO;
    }
    return YES;
}

- (NSArray *)querrySql:(NSString *)sql
{
    NSMutableArray * data = [NSMutableArray array];
    sqlite3_stmt *stmt;
    
    if (sqlite3_prepare_v2(_db, sql.UTF8String, -1, &stmt, NULL) == SQLITE_OK) {
        while (sqlite3_step(stmt)==SQLITE_ROW) {
            NSString * AQI = [NSString stringWithUTF8String:sqlite3_column_text(stmt, 1)];
            NSString * CO = [NSString stringWithUTF8String:sqlite3_column_text(stmt, 1)];
            NSString * NO2= [NSString stringWithUTF8String:sqlite3_column_text(stmt, 1)];
            NSString* SO2 = [NSString stringWithUTF8String:sqlite3_column_text(stmt, 1)];
            NSString * O3 = [NSString stringWithUTF8String:sqlite3_column_text(stmt, 1)];
            NSArray * arr=@[AQI,CO,NO2,SO2,O3];
            [data addObjectsFromArray:arr];
        }
    }
    return data;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initNet];
//        NSString * path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
//        NSString * filePath = [path stringByAppendingPathComponent:@"hour.plist"];
//        if (sqlite3_open(filePath.UTF8String, &_db) == SQLITE_OK) {
//            LOG(@"打开成功");
//        }else{
//            LOG(@"打开失败");
//        }
//        LOG(@"%@",path);
//        //创建数据库
//        NSString * sql = @"create table if not exists t_hour (id integer primary key autoincrement,aqi text,co text,no2 text,o3 text,so2 test);";
//        BOOL flag = [self exeSql:sql];
//        if (flag) {
//            LOG(@"创建成果");
//        }else{
//            LOG(@"创建失败");
//        }
//        NSArray * arr = [self querrySql:[NSString stringWithFormat:@"select * from t_hour limit 1 "]];
//        LOG(@"%@",arr);
    }
    return self;
}

- (void)refresh
{
    
    NSNumber * cityCode;
    NSString * cityName;
    if (!_currentCode) {
        cityCode = @(5101);
        cityName = @"成都";
    } else {
        cityCode = @([_currentCode integerValue]);
        cityName = _currentName;
    }
    [self update24HourWithCityCode:cityCode];
    [self getStation365DayAQIForApp:[NSString stringWithFormat:@"%@",cityCode]];
    [self updateData];
    [self updateWeatherCityName:cityName];
  
}

- (void)initNet
{
    [self getLocation];
    [self updateData];
}

/**获取城市实时数据*/
- (void)updateData
{
    [RJNetWork myNetRequestWithAddress:[NetURL defaultURL].GetCityRealTimeAQI data:@{} completeBlock:^(id responseObject) {
        NSArray * data = [responseObject objectForKey:@"data"];
        NSMutableDictionary * cityDic = [[NSMutableDictionary alloc] init];
        _city_pullutionDic = [NSMutableDictionary dictionary];
        _city_AQIValueDic = [NSMutableDictionary dictionary];
        NSMutableArray * cityArray = [NSMutableArray array];
        NSMutableArray * pollutantArray = [NSMutableArray array];
        NSMutableArray * aqiArray = [NSMutableArray array];
        
        for (NSUInteger i = 0; i < data.count; i ++) {
            NSDictionary * dic = [data[i] objectForKey:@"columns"];
            NSString * key = [dic objectForKey:@"CITYNAME"];
            [_city_pullutionDic setObject:dic[@"PRIMARYPOLLUTANT"] forKey:key];
            [_city_AQIValueDic setObject:dic[@"AQI"] forKey:key];
            NSString * code = [dic objectForKey:@"CITYCODE"];
            [cityArray addObject:@{code:key}];
            [cityDic setObject:dic forKey:key];
            [pollutantArray addObject:dic[@"PRIMARYPOLLUTANT"]];
            [aqiArray addObject:dic[@"AQI"]];
             NSString * cityName;
            if ([RJUserData defaultRJUserData].paoPaoName.length >=2 ) {
                cityName = [RJUserData defaultRJUserData].paoPaoName;
            }else{
                cityName = [RJUserData defaultRJUserData].currentCity;
            }
            if ([cityName isEqualToString:key]) {
                _currentPollutant = dic[@"PRIMARYPOLLUTANT"];
            }else{
               _currentPollutant = dic[@"PRIMARYPOLLUTANT"];
            }
        }
//        NSLog(@"%@,%ld",_city_pullutionDic,data.count);
        _cityAQIData = [NSDictionary dictionaryWithDictionary:cityDic];
        _citys = [NSArray arrayWithArray:cityArray];
        _currentName = (_currentName ? _currentName : [[_citys[0] allValues] lastObject]);
        _primaryPollutants = [NSArray arrayWithArray:pollutantArray];
        _AQIValues = [NSArray arrayWithArray:aqiArray];
//        _currentPollutant = _primaryPollutants[0];
        _currentAQIValue = _AQIValues[0];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateView" object:nil userInfo:@{@"result":@"1"}];
    }failBlack:^(id response) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateView" object:nil userInfo:@{@"result":@"0"}];
    }];
    
//    NSString *httpUrl = @"http://apis.baidu.com/apistore/weatherservice/weather";
//    NSString *httpArg = @"citypinyin=maerkang";
}

- (void)updateWeatherCityName:(NSString *)cityName
{
    NSString * pinyin;
    if ([cityName isEqualToString:@"成都"]) {
        pinyin = @"chengdu";
    } else {
        if ([RJUserData defaultRJUserData].paoPaoName.length >= 2) {
            pinyin = [RJTools getPinyinOfString:[RJUserData defaultRJUserData].paoPaoName];
        }else
        pinyin = [RJTools getPinyinOfString:cityName];
    }
    [self request:[NetURL defaultURL].GetWeather withHttpArg:[NSString stringWithFormat:@"citypinyin=%@",pinyin]];
}

-(void)request: (NSString*)httpUrl withHttpArg: (NSString*)HttpArg  {
    NSString *urlStr = [[NSString alloc]initWithFormat: @"%@?%@", httpUrl, HttpArg];
    NSURL *url = [NSURL URLWithString: urlStr];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
    [request setHTTPMethod: @"GET"];
    [request addValue: @"d97e2291a23c28c967b29b4ec7a47763" forHTTPHeaderField: @"apikey"];
    [NSURLConnection sendAsynchronousRequest: request
                                       queue: [NSOperationQueue mainQueue]
                           completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error){
                               if (error) {
                                   [[NSNotificationCenter defaultCenter] postNotificationName:@"updateWeather" object:nil userInfo:@{@"result":@"0",@"data":@{}}];
                        
                               } else {
                                   NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
                                   if (dic) {
                                       if (dic[@"errMsg"]) {
                                           return ;
                                       }
                                       [[NSNotificationCenter defaultCenter] postNotificationName:@"updateWeather" object:nil userInfo:@{@"result":@"1",@"data":dic[@"retData"]}];
                                   } else {
                                       [[NSNotificationCenter defaultCenter] postNotificationName:@"updateWeather" object:nil userInfo:@{@"result":@"0",@"data":@{}}];
                                   }
                               }
                           }];
}

/**获取城市详细数据*/
- (void)update24HourWithCityCode:(NSNumber *)cityCode
{
    [RJNetWork myNetRequestWithAddress:[NetURL defaultURL].GetCity24HourAQI data:@{@"cityCode":cityCode} completeBlock:^(id responseObject) {
        NSMutableArray * array = [[NSMutableArray alloc] init];
        for(NSDictionary * dic in responseObject) {
            NSDictionary * data = dic[@"data"];
            NSDictionary * columns = data[@"columns"];
            [array addObject:columns];
        }
        _city24Data = [NSArray arrayWithArray:array];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateLine" object:nil userInfo:@{@"result":@"1"}];
    }failBlack:^(id response) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateLine" object:nil userInfo:@{@"result":@"0"}];
    }];
}

/**手动设置城市*/
- (void)setCurrentCityCode:(NSNumber *)cityCode
{
    _currentCode = GetStringWithNum(cityCode);
    [self update24HourWithCityCode:cityCode];
    [self getStation365DayAQIForApp:[NSString stringWithFormat:@"%@",cityCode]];
}

#pragma mark -- 内部版24小时数据
//- (NSDictionary *)get24DataWithType:(NSString *)type
//{
//    NSMutableArray * array = [[NSMutableArray alloc] init];
//    NSMutableArray * timeArray = [[NSMutableArray alloc] init];
//    NSDictionary * exchangeDic = @{@"AQI":@"AQI",@"PM2.5":@"PM2_5",@"PM10":@"PM10",@"O₃":@"O3",@"SO₂":@"SO2",@"NO₂":@"NO2",@"CO":@"CO"};
//    NSString * key = exchangeDic[type];
//    if ([key isEqualToString:@"PM2.5"]) {
//        key = @"PM2_5";
//    }
//    
//    for (NSDictionary * dic in _city24Data) {
//        if (dic[key]) {
//            [array addObject:dic[key]];
//        }
//        if(dic[@"TIMEPOINT"]){
//            NSTimeInterval time = [dic[@"TIMEPOINT"] integerValue] / 1000;
//            NSString * timeString = [RJTools getTimeWithFormat:@"HH时" time:[NSDate dateWithTimeIntervalSince1970:time]];
//            [timeArray addObject:timeString];
//        }
//    }
//    NSDictionary * dataDic = @{[RJTools getTrueKeyTitlleWithTitle:type]:array};
//    return @{@"data":dataDic,@"times":timeArray};
//}

#pragma mark -- 公众版24小时数据
- (NSDictionary *)get24DataWithType:(NSString *)type
{
    if (!_city24Data) {
        return nil;
    }
    NSMutableArray * array = [[NSMutableArray alloc] init];
    NSMutableArray * colNumArr = [[NSMutableArray alloc] init];
    NSMutableArray * timeArray = [[NSMutableArray alloc] init];
    NSMutableArray * timePointArr = [NSMutableArray array];
    NSMutableArray * Inum = [NSMutableArray array];
    NSDictionary * exchangeDic = @{@"AQI":@"AQI",@"PM":@"PM2_5",@"PM10":@"PM10",@"O₃":@"O3",@"SO₂":@"SO2",@"NO₂":@"NO2",@"CO":@"CO"};
    NSString * colNum;
    NSString * key = exchangeDic[type];
    if ([type isEqualToString:@"PM₁₀"]) {
        key = @"PM10";
    }
    colNum = [NSString stringWithFormat:@"%@",key];
    if ([key isEqualToString:@"PM2.5"]) {
        key = @"PM2_5";
    }
    if ([key isEqualToString:@"AQI"]) {
        colNum = @"AQI";
    }
    NSString * Ikey = [key isEqualToString:@"AQI"]?key:[NSString stringWithFormat:@"%@%@",@"I",key];
    for (NSInteger i = 0; i < _city24Data.count; i ++) {
        NSDictionary * dic = _city24Data[i];
        if (dic[key]) {
            [array addObject:dic[key]];
            NSString * Istr = dic[Ikey];
            if ([Istr isKindOfClass:[NSNull class]]||[Istr isEqualToString:@"—"]) {
                [Inum addObject:@"0"];
            }else{
                [Inum addObject:dic[Ikey]];
            }
                [colNumArr addObject:dic[colNum]];
        }
        if (!dic[key]) {
            [array addObject:@"0"];
            [colNumArr addObject:@"0"];
            [Inum addObject:@"0"];
        }
        if(dic[@"TIMEPOINT"]){
            NSTimeInterval time;
            if (DeviceType < 5) {
                time = [dic[@"TIMEPOINT"] floatValue] / 1000;
            }else{
                time = [dic[@"TIMEPOINT"] integerValue] / 1000;
            }
            [timePointArr addObject:dic[@"TIMEPOINT"]];
            NSString * timeString = [RJTools getTimeWithFormat:@"yyyy-MM-dd HH:mm" time:[NSDate dateWithTimeIntervalSince1970:time]];
            [timeArray addObject:timeString];
        }
        //当当天时间不存在时
        if (!dic[@"TIMEPOINT"]) {
            if (i > 0) {
//                NSDictionary * befDic = [timePointArr lastObject];
                NSTimeInterval  todayTime = [[timePointArr lastObject] floatValue]+OnedayMS;
                [timePointArr addObject:[NSString stringWithFormat:@"%lf",todayTime]];
                NSTimeInterval todayTimeS ;
                if (DeviceType < 5) {
                    todayTimeS = todayTime / 1000;
                }else{
                    todayTimeS = todayTime/ 1000;
                }
                NSString * timeString = [RJTools getTimeWithFormat:@"yyyy-MM-dd HH:mm" time:[NSDate dateWithTimeIntervalSince1970:todayTimeS]];
                [timeArray addObject:timeString];
            }
        }
    }
    NSString * max = [self getMax:array];
    NSArray * resultArr = @[array,timeArray,Inum];
    return @{type:resultArr,@"max":max};
}

- (void)getStation365DayAQIForApp:(NSString *)cityCode
{
    if (!cityCode) {
        return;
    }
    [RJNetWork myNetRequestWithAddress:[NetURL defaultURL].Get356DayAQI data:@{@"cityCode":cityCode} completeBlock:^(id responseObject) {
        _oneYear = responseObject;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"OUtOneYearData" object:nil userInfo:@{@"result":@"1"}];
    } failBlack:^(id response) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"OUtOneYearData" object:nil userInfo:@{@"result":@"0"}];
    }];
}

- (NSDictionary *)get365dataWithType:(NSString *)type
{
    if (!_oneYear) {
        return nil;
    }
    NSDictionary * exchangeDic = @{@"AQI":@"AQI",@"PM":@"PM2_5",@"PM₁₀":@"PM10",@"O₃":@"O3",@"SO₂":@"SO2",@"NO₂":@"NO2",@"CO":@"CO"};
    NSString * key = exchangeDic[type];
    NSString * Ikey = [key isEqualToString:@"AQI"]?key:[NSString stringWithFormat:@"%@%@",@"I",key];
    NSMutableArray * dataArr = [NSMutableArray array];
    NSMutableArray * timeArr = [NSMutableArray array];
    NSMutableArray * Inum = [NSMutableArray array];
    for (NSInteger i = 0; i < _oneYear.count; i ++) {
        NSDictionary * dic = _oneYear[i];
        [dataArr addObject:dic[key]];
        NSString * Istr = dic[Ikey];
        if ([Istr isKindOfClass:[NSNull class]]||[Istr isEqualToString:@"—"]) {
           [Inum addObject:@"0"];
        }else{
           [Inum addObject:dic[Ikey]];
        }
        NSString * timeStr = dic[@"TIMEPOINT"];
        NSString * time = [timeStr substringWithRange:NSMakeRange(0, 10)];
        [timeArr addObject:time];
    }
    NSString * max = [self getMax:dataArr];
    NSArray * resultArr = @[dataArr,timeArr,Inum];
    return @{type:resultArr,@"max":max};
    
}
- (NSArray *)getCityDetailData
{
    NSMutableArray * array = [[NSMutableArray alloc] init];
    for (NSDictionary * dic in _city24Data) {
        NSArray * allkeys = [dic allKeys];
        NSMutableDictionary * trueDic = [[NSMutableDictionary alloc] init];
        for (NSString * key in allkeys) {
            if ([self isKeyData:key]) {
                [trueDic setObject:dic[key] forKey:key];
            }
        }
        [array addObject:trueDic];
    }
    return array;
}

- (BOOL)isKeyData:(NSString *)key
{
    NSArray * keys = @[@"PM2_5",@"PM10",@"O3",@"SO2",@"NO2",@"CO"];
    if ([keys indexOfObject:key] != NSNotFound) {
        return YES;
    }
    return NO;
}

/**获取位置*/
- (void)getLocation
{
    if (!_currentLocation) {

        if ([CLLocationManager locationServicesEnabled]) {
            _currentLocation = [[CLLocationManager alloc]init];
            _currentLocation.delegate = self;
            //        NSLog(@"PURPOSE = %@",self.myLocationManager.purpose);
            //选择定位的方式为最优的状态，他又四种方式在文档中能查到
            _currentLocation.desiredAccuracy=kCLLocationAccuracyBest;
            //发生事件的最小距离间隔
            _currentLocation.distanceFilter = kCLDistanceFilterNone;
            [_currentLocation requestAlwaysAuthorization];
            [self updateLocation];
        } else {
            
        }
    }
}

- (void)updateLocation
{
#warning 不要定位
//    [_currentLocation startUpdatingLocation];
    _isLocationDown = YES;
#warning 不要定位
    //    if (![RJUserData defaultRJUserData].isProvince) {
    //        [RJUserData defaultRJUserData].paoPaoName = @"成都";
    //    }
    if (![RJUserData defaultRJUserData].isProvince) {
        NSString * city = [RJUserData defaultRJUserData].currentCity;
        NSArray * cityArr = @[@"成都",@"自贡",@"攀枝花",@"泸州"	,@"德阳",@"绵阳",@"广元",	@"遂宁",@"内江",@"乐山",@"南充",@"眉山"	,@"宜宾",@"广安",@"达州",@"雅安",@"巴中",@"资阳",@"马尔康",@"康定",@"西昌"];
        for (NSString * str in cityArr) {
            if ([city rangeOfString:str].location != NSNotFound) {
                [RJUserData defaultRJUserData].paoPaoName = str;
                break;
            }
        }
    }else{
        if ([RJUserData defaultRJUserData].paoPaoName.length >=2) {
            
        }else{
            [RJUserData defaultRJUserData].paoPaoName = @"成都";
        }
    }
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"didGetLocation" object:nil userInfo:@{@"result":@NO,@"error":@"定位失败"}];
}

#pragma mark - LocationDelegete
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    _isLocationDown = YES;
#warning 不要定位
//    if (![RJUserData defaultRJUserData].isProvince) {
//        [RJUserData defaultRJUserData].paoPaoName = @"成都";
//    }
    if (![RJUserData defaultRJUserData].isProvince) {
        NSString * city = [RJUserData defaultRJUserData].currentCity;
        NSArray * cityArr = @[@"成都",@"自贡",@"攀枝花",@"泸州"	,@"德阳",@"绵阳",@"广元",	@"遂宁",@"内江",@"乐山",@"南充",@"眉山"	,@"宜宾",@"广安",@"达州",@"雅安",@"巴中",@"资阳",@"马尔康",@"康定",@"西昌"];
        for (NSString * str in cityArr) {
            if ([city rangeOfString:str].location != NSNotFound) {
                [RJUserData defaultRJUserData].paoPaoName = str;
                break;
            }
        }
    }else{
       [RJUserData defaultRJUserData].paoPaoName = @"成都";
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"didGetLocation" object:nil userInfo:@{@"result":@NO,@"error":@"定位失败"}];
    
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    [_currentLocation stopUpdatingLocation];
    _checkinLocation = [locations lastObject];
    CLGeocoder * gCoder = [[CLGeocoder alloc] init];
    [gCoder reverseGeocodeLocation:_checkinLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        _isLocationDown = YES;
        if (!error && [placemarks count] > 0)
        {
            NSDictionary *dict = [[placemarks lastObject] addressDictionary];
            _cityName = [dict objectForKey:@"City"];
            NSRange shiRange = [_cityName rangeOfString:@"市"];
            NSRange xianRange = [_cityName rangeOfString:@"县"];
            if (shiRange.location != NSNotFound) {
                _cityName = [_cityName substringToIndex:shiRange.location];
            }
            if (xianRange.location != NSNotFound) {
                _cityName = [_cityName substringToIndex:xianRange.location];
            }
            _sublocality = [dict objectForKey:@"SubLocality"];
#warning 不要定位
//            if (![RJUserData defaultRJUserData].isProvince) {
//              [RJUserData defaultRJUserData].paoPaoName = _cityName;
//            }
            if (![RJUserData defaultRJUserData].isProvince) {
                NSString * city = [RJUserData defaultRJUserData].currentCity;
                NSArray * cityArr = @[@"成都",@"自贡",@"攀枝花",@"泸州"	,@"德阳",@"绵阳",@"广元",	@"遂宁",@"内江",@"乐山",@"南充",@"眉山"	,@"宜宾",@"广安",@"达州",@"雅安",@"巴中",@"资阳",@"马尔康",@"康定",@"西昌"];
                for (NSString * str in cityArr) {
                    if ([city rangeOfString:str].location != NSNotFound) {
                        [RJUserData defaultRJUserData].paoPaoName = str;
                        break;
                    }
                }
            }else{
                [RJUserData defaultRJUserData].paoPaoName = @"成都";
            }
            dispatch_async(dispatch_get_main_queue(), ^{
#warning 不要定位
//                            [[NSNotificationCenter defaultCenter] postNotificationName:@"didGetLocation" object:nil userInfo:@{@"result":@YES,@"CityName":_cityName,@"Location":_sublocality}];
                 [[NSNotificationCenter defaultCenter] postNotificationName:@"didGetLocation" object:nil userInfo:@{@"result":@NO,@"error":@"定位失败"}];
            });

        } else {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"didGetLocation" object:nil userInfo:@{@"result":@NO,@"error":@"定位失败"}];
        }
    }];
}

- (void)getBottomDataWithCityCode:(NSString *)cityCode
{
    NSString * url = [NSString stringWithFormat:@"http://www.scnewair.cn:3389/publish/getCityInfoCForApp?cityCode=%@",cityCode];
    [RJNetWork sendNetworkRequestWithUrl:url Dic:@{} Complete:^(BOOL succeed, id responseObject) {
            NSDictionary * columns = responseObject[@"columns"];
            NSDictionary * stationRealTimeAQ = columns[@"STATIONREALTIMEAQI"];
            _allAQIArray = [NSArray arrayWithArray:stationRealTimeAQ[@"data"]];
            //            NSDictionary * stationDay = columns[@"STATIONDAYAQI"];
            NSDictionary * data = stationRealTimeAQ[@"data"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"OutPositionValueIsGet" object:data];
//        }
//        _currentType = @"AQI";
//        [self changeMapWithType:_currentType];
     
    }];
}

#pragma mark -- 求数组中最大值
- (NSString *)getMax:(NSArray *)arr
{
    NSComparator cmptr = ^(id obj1, id obj2){
        if ([obj1 floatValue] > [obj2 floatValue]) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        if ([obj1 floatValue] < [obj2 floatValue]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    };
    
    NSArray *array = [arr sortedArrayUsingComparator:cmptr];
    NSString *max = [array lastObject];
    return max;
}
@end
